package com.hm.common.plugin.oss.qiniu;

import com.google.gson.Gson;
import com.hm.common.autoconfigure.CommonProperties;
import com.hm.common.plugin.oss.OssCloudAbs;
import com.hm.common.su.exception.ErrorCode;
import com.hm.common.su.exception.ServiceException;
import com.hm.common.su.util.CommonUtil;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * @author shishun.wang
 * @version 1.0
 * @date 2019/4/2 17:29
 * @describe
 */
@Slf4j
public class QiNiuCloudPlugin implements OssCloudAbs {
	
	private CommonProperties commonProperties;
	
	public QiNiuCloudPlugin(CommonProperties commonProperties){
		this.commonProperties = commonProperties;
	}
	
	public String upload(String fileName, byte[] uploadBytes){
		if (CommonUtil.isAnyEmpty(fileName,uploadBytes)){
			throw ServiceException.warning(ErrorCode.REQUIRED_PARAMETERS_MISSING);
		}
		try{
			CommonProperties.Plugin.OssCloudConfig ossCloudConfig = commonProperties.getPlugin().getOssCloudConfig();
			
			UploadManager uploadManager = new UploadManager(new Configuration());
			Auth auth = Auth.create(ossCloudConfig.getAccessKey(), ossCloudConfig.getSecretKey());
			String upToken = auth.uploadToken(ossCloudConfig.getBucket());
			
			Response response = uploadManager.put(uploadBytes, fileName, upToken);
			DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
			return putRet.key;
		}catch (Exception e){
			log.error("qi niu cloud upload file failed",e);
			throw ServiceException.warning(ErrorCode.SYSTEM_ERROR);
		}
	}
}
